import { type } from "os";
import { reactive, Ref, ref, unref, watch } from "vue";

type IParamsType<T> = { [D in keyof T]?: Ref<T[D]> | T[D] };
export const useTable = <T extends { list: any; total: any }, P>(
  // 根据函数去推定义的泛型
  listRequestApi: (data: P) => IResponseData<T>,
  queryParams: IParamsType<P>
) => {
  const tableList = ref<T["list"]>([]);
  const pagination = reactive({
    total: 0,
    currentPage: 1,
    currentSize: 10,
  });
  const query = {} as P;
  watch(
    () => queryParams,
    (val) => {
      console.log(val);
      for (const key in val) {
        // console.log(val);
        query[key] = unref(val[key]) as P[Extract<keyof P, string>];
        // getRoleList();
      }
    },
    { deep: true }
  );
  //   console.log(query);

  const getTableList = async () => {
    let res = await listRequestApi({
      pageNum: pagination.currentPage,
      pageSize: pagination.currentSize,
      ...query,
    });
    if (res.code === 200) {
      tableList.value = res.data.list;
      pagination.total = res.data.total;
    }
  };
  getTableList();
  const handleSizeChange = (size: number) => {
    pagination.currentSize = size;
    getTableList();
  };
  const handleCurrentChange = (page: number) => {
    // console.log(page);
    pagination.currentPage = page;
    getTableList();
  };

  const searchListContent = () => {
    getTableList();
  };

  return {
    getTableList,
    pagination,
    tableList,
    // unitPage,
    handleSizeChange,
    handleCurrentChange,
    searchListContent,
  };
};
